package com.segmentfault.mvc.controller;

import com.segmentfault.mvc.entity.GoodsEntity;
import com.segmentfault.mvc.service.IGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private IGoodsService goodsService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model){
        List<GoodsEntity> goodsList = goodsService.findAll();

        model.addAttribute("goodsEntities", goodsList);
        return "goods-list";
    }

    @RequestMapping(value = "/goods-add", method = RequestMethod.GET)
    public String toGoodsAdd() {
        return "goods-add";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addGoods(GoodsEntity goodsEntity){
        goodsService.add(goodsEntity);
        return "redirect:/goods/list";
    }

    @RequestMapping(value = "/goods-update", method = RequestMethod.GET)
    public String toGoodsUpdate(Model model,Long goodsId) {
        GoodsEntity goods = goodsService.findById(goodsId);
        model.addAttribute("goods", goods);
        return "goods-update";
    }
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String  updateGoods(GoodsEntity goodsEntity){
        goodsService.modify(goodsEntity);
        return "redirect:/goods/list";
    }
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String deleteGoods(Long goodsId) {
        goodsService.remove(goodsId);
        return "redirect:/goods/list";
    }
}
